<template>
  <div class="productsMain" curpagename="productsMain1123234343423423" v-loading="allLoading">
    <div class="left_block">
      <el-scrollbar height="calc(100vh - 178px)">
        <div class="product_block">
          <!-- pro_item -->
          <div
            v-if="colorArr.length"
            class="color_item"
            v-for="(cItem, cIndex) in colorArr"
            :key="cIndex"
            :class="{ activeItem: cIndex == activeIndex }"
            @click="getColorProduct(cItem, cIndex)"
          >
            <div class="color_pic">
              <img :src="cItem.file_url" />
              <div class="color_txt">{{ cItem.name }}</div>
            </div>
          </div>
          <div v-else class="pro_item" v-for="(pItem, pIndex) in productArr" :key="pIndex"  :class="{ activeItem: pIndex == activeIndex }"
            @click="getColorProduct(pItem, pIndex)">
            <div class="item_name">
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="pItem.size"
                placement="top-end"
                v-if="pItem.size"
              >
                <span>{{ pItem.name }}</span>
              </el-tooltip>
              <span v-else>{{ pItem.name }}</span>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="right_block" v-loading="loadingRight" v-if="!allLoading">
      <div class="title_tip">
        <span class="fail_info" @click="getErrData" v-if="isEditPicture&&lookErr"
          ><el-icon><Warning /></el-icon>查看上传失败图片</span
        >

        <!-- <span class="tip_info" @click="oprationFun"
          ><el-icon><QuestionFilled /></el-icon>操作指南</span
        > -->

        <div class="btnBox">
          <el-button v-if="!isEditPicture&&activeLeftObj"  v-auth="{'authArr':authArr,'key':'edit'}"  type="primary" link @click="editOpen"  style="margin-right:-25px;">
            <el-icon><Edit /></el-icon>   {{$t('merak.edit')}}
          </el-button>
          <el-button style="margin-left: 20px" type="default" v-if="isEditPicture" @click="cancelEdit">    {{$t('merak.back')}} </el-button>
        </div>
      </div>

      <!-- 查看 -->
      <div style="margin-top:20px;margin-left:-15px;margin-right:-15px;" v-if="!isEditPicture">
        <productLook v-model="dfaultFileArr"></productLook>
      </div>
 
    <!-- 上传列表  -->
      <div class="upload_moudle" v-if="isEditPicture"> 
    
        <productFileList
       
          ref="productFileRef"
           :refname="productFileRef"
          v-bind="uploadDataOne"
          v-model="dfaultFileArr"
          @delLine="delLineFun"
          @dragChange="dragChange"
          @setDefault="setDefaultFun"
          @errFile="errFile"
        ></productFileList>
      </div>

      <Transition name="fade" mode="out-in">
        <errorFileList v-if="errInfoBool" :errDataArr="errDataArr" @close="handleClose" />
      </Transition>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick } from "vue";
import productLook from "@/views/goodsArchive/a-components/pictureLook/look.vue";
import productFileList from "@/views/goodsArchive/a-components/productDetailFile/index.vue";
import errorFileList from "@/views/goodsArchive/a-components/errorDetailFle/index.vue";

import { Path, getListSpuApi, delGoodsImagesApi, changesImagesApi, getListTabApi } from "@/api/modules/goodsArchive/list/detail";

import { successMsg, failMsg, confirmWarningMsg, warnMsg,infoMsg } from "@/utils/messageUtils";
import { ResultEnum } from "@/enums/httpEnum";

let dfaultFileArr = ref([]); //初始化默认数据
const productFileRef = ref(null); //组件ref

const props = withDefaults(
  defineProps<{
    goodsId: string;
    authArr:object;
  }>(),
  {}
);
console.log(props)
const allLoading=ref(true);
//左侧初始化
const colorArr = ref([]);
const productArr = ref([]);
const activeIndex = ref(0); //选中索引
const activeLeftObj = ref({}); //选中对象值
//右侧图片
const loadingRight = ref(false);
const isEditPicture = ref(false);
const draggingBool = ref(false);
const uploadDataOne = reactive({
   accept: ".jpg,.jpeg,.png,.gif,.bmp,.webp", //只允许图片上传
   tipMsg:',支持jpg、png、webp格式',
  type: "main",
  path: Path.goodsImgSpu,
  params: { goods_id: props.goodsId },
  isEdit: isEditPicture, //是否编辑
  occupyHei: 55, //父页面占用高度
  draggingBool: draggingBool, //烤漆拖拽
  imageType: "squire",
  imageProps: { minWidth: 800, maxWidth: 1000 },
  failBoolShow:true,
});

//删除一行
const delLineFun = params => {
  confirmWarningMsg({
    msg: "是否确认删除?",
    callback: val => {
      console.log(val, "成功confirm还是失败cancel");
      if (val == "confirm") {
        let rows = params.rows;

        delGoodsImagesApi({ id: rows.id, source: "spu" }).then(res => {
          console.log(res);
          if (res.code == ResultEnum.SUCCESS) {
            let indexFilter = dfaultFileArr.value.findIndex(fitem => fitem.id == rows.id);
            if (indexFilter > -1) {
              dfaultFileArr.value.splice(indexFilter, 1);
            }
            productFileRef.value.delChangeFile(rows); //清空上次选择
            successMsg("删除成功");
          } else {
            failMsg(res.message);
          }
        });
      }
    }
  });
};

//错误数据
const errInfoBool = ref(false);
const errDataArr = ref([]);
const getErrData = () => {
  let errData = productFileRef.value.getErrUploadData();

  if (errData && errData.length > 0) {
    errDataArr.value = errData;
    errInfoBool.value = true;
    return;
  }
  warnMsg("未有上传失败的图片");
};

const handleClose = () => {
  {
    errInfoBool.value = false;
  }
};

//拖拽
const dragChange = params => {
  console.log(params, "腹肌拖拽数据");
  let moveObj = params.moveObj.moved;
  let dataObj = {
    goods_id:props.goodsId,
    source: "spu",
    id: moveObj.element?.id,
    sort: moveObj.newIndex + 1,
    is_default: moveObj.element?.is_default
  };

  changesImagesApi(dataObj).then(res => {
    let { code, data, message } = res;
    if (code == ResultEnum.SUCCESS) {
      productFileRef.value?.resetArr();
      nextTick(() => {
        // console.log(productFileRef.value);
        // productFileRef.value?.dragScroll(100 * moveObj.newIndex);
      });
    }
  });
};

//设为主图
const setDefaultFun = item => {
  console.log(item);
  let dataObj = {
    goods_id:props.goodsId,
    source: "spu",
    id: item.id,
    is_default: 1,
    // sort: item.sort
  };
  changesImagesApi(dataObj).then(res => {
    let { code, data, message } = res;
    if (code == ResultEnum.SUCCESS) {
      successMsg(message);
      //  initSpuImages();
    } else {
      failMsg(message);
      // initSpuImages();
    }
  });
};
// source ： spu 或 detail  区分来源页面：商品图，detail详情图
// id: 图片id
// sort: 1 序号
// is_default: 1 或 0  此参数 source=spu时才会有。详情图没有默认设置。1默认，0非默认

//#region 左侧

//左侧初始化
let initLeftConfig = () => {
    allLoading.value=true;
  // loadingRight.value = !allLoading.value;

  getListTabApi({ goods_id: props.goodsId }).then(res => {
    let { code, data, message } = res;
    if (code == ResultEnum.SUCCESS) {
      let list = data.list;
      colorArr.value = list.color;
      productArr.value = list.product;
      if( !list.color.length && ! list.product){
          loadingRight.value = false;
        return;
      }
      if (list.color.length) {
        //有颜色先选择
        activeLeftObj.value = list.color[0]; //默认选中第一个
        initRight();
        return;
      }
      activeLeftObj.value = list.product[0]; //默认选中第一个
      if(activeLeftObj.value){ 
        activeLeftObj.value.index="0";
      }
      initRight();
    } else {
      failMsg(message);
    }
  });
};
const mainShow=ref(false);
const getColorProduct = (item, index) => {
 
  activeIndex.value = index;
  activeLeftObj.value = item;
  mainShow.value=false;
  nextTick(()=>{
    loadingRight.value=true;
     
       initRight();
  })

};
//初始化right
const initRight = () => {
  isEditPicture.value = false;
  draggingBool.value = false;
  // loadingRight.value = true;
  let paramsObj = {
    goods_id: props.goodsId,
    color: activeLeftObj.value?.color,
    product_id: activeLeftObj.value?.product_id
  };
 
  uploadDataOne.params = paramsObj;
  dfaultFileArr.value = [];
  initSpuImages();
};
//#endregion

//初始化商品详情图片列表
const initSpuImages = () => {
  //  "color":227,
  // "product_id":0

  let paramsObj = {
    goods_id: props.goodsId,
    // color: activeLeftObj.value?.color,
    // product_id: activeLeftObj.value?.product_id
  };
  if(activeLeftObj.value?.color){
    paramsObj.color=activeLeftObj.value?.color;
  }else{
    paramsObj.product_id=activeLeftObj.value?.product_id;
    paramsObj.index=activeLeftObj.value?.index;
  } 
  getListSpuApi(paramsObj).then(res => {
     allLoading.value=false;
    let { code, data, message } = res;
    if (code == ResultEnum.SUCCESS) {
      let list = data.table_data?.list;
      
      if(list.length){
            dfaultFileArr.value = list.map(lItem => {
        return {
          ...lItem,
          currentDefault: lItem.is_default == 1
        };
      });
       
      }else{
         dfaultFileArr.value = [];
      }
     mainShow.value=true;
    } else {
        failMsg(message)
    }
    
    loadingRight.value = false;
  });
};

//开启编辑
const editOpen = () => {
  isEditPicture.value = true;
  draggingBool.value = true;
};
//取消编辑
const cancelEdit = () => {
  isEditPicture.value = false;
  draggingBool.value = false;
  initLeftConfig()
};


const lookErr=ref(false);
const errFile=()=>{ 
   let errData = productFileRef.value.getErrUploadData(); 
     if(errData.length ) lookErr.value=true;
}

onMounted(() => {
  initLeftConfig();
  //   initSpuImages();
});
</script>
<style lang="scss" scoped>
@import url("./index.scss");
</style>
